<template>
    <div>
      <div class="xiaoqu">
        <el-row>
          <el-col :span="6">
            用户名称：<el-input
              style="width: 200px; height: 38px"
              clearable
              v-model="name"
            />
          </el-col>
          <el-col :span="9">
                预约时间：
                <el-date-picker v-model="select.time" start-placeholder="开始日期"
                  style="width: 72%; height: 38px;" />
        </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              style="height: 38px; width: 70px"
              @click="search"
              >搜索</el-button
            >
          </el-col>
        </el-row>
        <el-row class="col" style="margin-top: 20px">
          <el-button type="primary" @click="insert">新增预约</el-button>
        </el-row>
        <el-row class="col" style="margin-top: 20px">
          <el-table
            :data="yuyueList"
            border
            style="width: 100%; text-align: center"
            :header-cell-style="{
              backgroundColor: '#1890ff',
              color: 'white',
              textAlign: 'center',
              height: '50px',
            }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column prop="yuyueId" label="ID" />
            <el-table-column prop="userChen.username" label="用户名" />
            <el-table-column prop="yuyueType" label="预约类型" />
            <el-table-column prop="yuyueTime" label="预约时间" />
            <el-table-column prop="yuyueContent" label="预约内容" />
            <el-table-column prop="yuyueDel" label="预约状态" >
              <template #default="scope">
              <el-tag :type="scope.row.yuyueDel === 1? 'success' : 'danger'">
                {{ scope.row.yuyueDel === 1? '已处理' : '未处理' }}
              </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" class="text" plain @click="edite(scope.row)">修改信息</el-button>
                <el-button type="text" class="text" plain @click="open(scope.row)">删除预约</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>

      <el-dialog v-model="InsertDialog" title="新增预约">
      <XinZeng @yuyueData="handleYuyueData"></XinZeng>
      <template #footer>
        <el-button class="text" @click="cancelInsert">取消</el-button>
        <el-button type="primary" @click="InsertYuyue()">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="UpDateDialog" title="修改信息" >
      <XiuGai :key="yuyueAll.yuyueId" @yuyueData="handle" :data="yuyueAll"></XiuGai>
      <template #footer>
        <el-button class="text" @click="cancelupdate">取消</el-button>
        <el-button type="primary" @click="updateYuyue()">保存</el-button>
      </template>
    </el-dialog>

    </div>
  </template>
  
      <script setup>
      import { ref,onMounted,reactive} from 'vue';
      import axios from 'axios';
      import qs from 'qs';
      import { ElMessage, ElMessageBox } from 'element-plus'
      import XinZeng from './components/XinZeng.vue';
      import XiuGai from './components/XiuGai.vue';
      // import dayjs from 'dayjs';

      const yuyueList = ref([]); 
      const id=ref(null);
      const name = ref(''); 
      const select = reactive({ 
        name: '',
        time: '',
      });
      const InsertDialog = ref(false);
      const UpDateDialog = ref(false);
      const yuyue = ref([]);
      const yuyueData=ref([]);
      const yuyueAll=ref([]);

      //搜索
      const search = async function(){
        let time=formatTimeStamp(select.time);
        console.log(time);
        await axios.post('http://localhost:8080/yuyue/searchTime', 
            qs.stringify({ time:time,name: name.value })
        ).then(response => {
          console.log(response);
          response.data.data.forEach((item) => {
            item.yuyueTime = formatTimeStamp(item.yuyueTime);
          });
          yuyueList.value = response.data.data;
        }). catch (error=> {
          console.error('发送数据出错：', error);
        });
      };

      //新增预约
    const handleYuyueData = (data) => {
      console.log(data);
      yuyue.value = data;
    };
    const insert = () => {
      InsertDialog.value = true;

    };
    const cancelInsert = () => {
      InsertDialog.value = false;
    }

    const InsertYuyue = async () => {
      InsertDialog.value = false;
      console.log(yuyue.value);
      try{
         await axios.post('http://localhost:8080/yuyue/insert',qs.stringify({
            yuyueTime:yuyue.value.time,
            yuyueUid:yuyue.value.id,
            yuyueType:yuyue.value.type,
            yuyueContent:yuyue.value.content,
          })
        );
        ElMessage({
          type: 'success',
          message: '新增成功'
        });
        location.reload();
      }catch(error){
        console.log(error);
      }
    }
      //修改预约
      const edite = (data) => {
      console.log(data);
      yuyueAll.value = data;
      UpDateDialog.value=true;
    };
    const cancelupdate = () =>{
      UpDateDialog.value=false;
    };
    const handle = (data) => {
      console.log(data);
      yuyueData.value = data;
    };
    const updateYuyue = async () => {
      UpDateDialog.value=false;
      formatTimeStamp(yuyueData.value.yuyueTime);
      console.log(yuyueData.value);
      try{
        await axios.post('http://localhost:8080/yuyue/update',qs.stringify({
          ...yuyueData.value})
        );
        ElMessage({
          type: 'success',
          message: '修改成功'
        });
         location.reload();
      }catch(error){
        console.log(error);
      }
    }

      //时间格式化
      const formatTimeStamp = (timestamp) => {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      }
        
      //删除预约
      const open = async (data)=>{
        id.value = data.yuyueId;
        
        try {
            const confirmDelete = await ElMessageBox.confirm(
                '确定删除该预约吗？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            );

            if (confirmDelete === 'confirm') {
                const response = await axios.post('http://localhost:8080/yuyue/delete', qs.stringify({ id: id.value }));
                console.log(response);

                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });

                // 使用setTimeout来异步执行location.reload()，避免一些潜在的冲突
                setTimeout(() => {
                    location.reload();
                }, 0);
            } else {
                ElMessage({
                    type: 'info',
                    message: '已取消删除',
                });
            }
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '删除失败',
            });

            // console.error('Error during delete operation:', error);
        }
        // console.log(id.value);
        // const confirmDelete= await ElMessageBox({
        //   title: '提示',
        //   message: '确定删除该预约吗？',
        //   showCancelButton: true,
        //   type: 'warning',
          
        // });
        // if(confirmDelete==='confirm'){
        //   try{
        //     const response=await axios.post('http://localhost:8080/yuyue/delete',qs.stringify({id: id.value}));
        //     console.log(response);
            
        //     ElMessage({
        //       type: 'success',
        //       message: '删除成功'
        //     });
        //     setTimeout(() => {
        //         location.reload();
        //     }, 0);
        //   } catch(error){
        //     ElMessage({
        //       type: 'error',
        //       message: '删除失败'
        //     });
        //   }
        // }else{
        //   ElMessage({
        //     type: 'info',
        //     message: '已取消删除'
        //   });
        // }
      };
      //初次加载
      onMounted(() => {
        axios.get('http://localhost:8080/yuyue/select').then(response => {
          response.data.data.forEach((item) => {
            item.yuyueTime = formatTimeStamp(item.yuyueTime);
          });
          yuyueList.value = response.data.data;
          yuyueList.value.sort((a, b) => b.yuyueId - a.yuyueId);
        }).catch(error => {
          console.error("获取区域数据时出现错误：", error);
        });
        
      });
  
      </script>
      
      <style lang="less" scoped>
  </style>
  